package com.squareup.picasso;

import android.content.ContentResolver;
import android.content.Context;
import android.content.UriMatcher;
import android.net.Uri;
import android.provider.ContactsContract;

import com.squareup.picasso.Picasso.LoadedFrom;

import java.io.IOException;
import java.io.InputStream;

final class ContactsPhotoRequestHandler extends RequestHandler {
    private static final UriMatcher matcher;
    private final Context context;

    static {
        matcher = new UriMatcher(-1);
        matcher.addURI("com.android.contacts", "contacts/lookup/*/#", 1);
        matcher.addURI("com.android.contacts", "contacts/lookup/*", 1);
        matcher.addURI("com.android.contacts", "contacts/#/photo", 2);
        matcher.addURI("com.android.contacts", "contacts/#", 3);
        matcher.addURI("com.android.contacts", "display_photo/#", 4);
    }

    ContactsPhotoRequestHandler(Context context) {
        this.context = context;
    }

    public final boolean canHandleRequest(Request result) {
        Uri uri = result.uri;
        return !"content".equals(uri.getScheme())
                || !ContactsContract.Contacts.CONTENT_URI.getHost().equals(uri.getHost())
                || ContactsPhotoRequestHandler.matcher.match(result.uri) == -1 ? false : true;
    }

    public final Result load(Request request) throws IOException {
        ContentResolver contentResolver = this.context.getContentResolver();
        Uri uri = request.uri;
        InputStream inputStream;
        switch (ContactsPhotoRequestHandler.matcher.match(uri)) {
            case 1: {
                uri = ContactsContract.Contacts.lookupContact(contentResolver, uri);
                if (uri == null) {
                    inputStream = null;
                } else {
                    inputStream = ContactsContract.Contacts.openContactPhotoInputStream(contentResolver, uri, true);
                }
                break;
            }
            case 3: {
                inputStream = ContactsContract.Contacts.openContactPhotoInputStream(contentResolver, uri, true);
                break;
            }
            case 2:
            case 4: {
                inputStream = contentResolver.openInputStream(uri);
                break;
            }
            default:
                throw new IllegalStateException("Invalid uri: " + uri);
        }


        Result result = inputStream != null ? new Result(inputStream, LoadedFrom.DISK) : null;
        return result;
    }
}

